<template>
  <div>
    <div class="request" v-if="!requestAddShow && !requestDtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'Order'"
          v-hasPermi="['system:order:query']"
          class="btn search"
          @click="getRequestList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'OrderCheck'"
          v-hasPermi="['system:orderCheck:query']"
          class="btn search"
          @click="getRequestList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:order:add']"
          class="btn search"
          v-if="route.name === 'Order'"
          @click="
            requestAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn save" @click="handleExport()"
          ><el-icon class="icon" color="#fff"> <Download /> </el-icon
          >导出</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="purchaseOrderCode">采购编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDate">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantName">采购人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">采购部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseOrderTypeName">采购类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseNumSum">采购数量</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseAmountSum">采购总金额(元)</el-checkbox>
            </div>
            <div>
              <el-checkbox label="orderCheckStatusName">审核状态</el-checkbox>
            </div>

            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.purchaseOrderCode"
            class="search-input"
            placeholder="请输入采购订单编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicantName"
            class="search-input"
            placeholder="请输入采购人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.purchaseOrderType"
            placeholder="请选择采购类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in typeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.orderCheckStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in checkOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-date-picker
            v-model="params.applicantDate"
            format="YYYY/MM/DD"
            class="search-input"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择申请日期"
          />
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="requestList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <!-- <div class="table-operate">
              <el-icon
                v-hasPermi="['erp:request:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-hasPermi="['erp:request:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>

              <el-icon
                v-hasPermi="['erp:request:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> -->

            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'Order' &&
                  [0, 5, 6].includes(row.orderCheckStatus)
                "
                v-hasPermi="['system:order:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="route.name === 'Order'"
                v-hasPermi="['system:order:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="route.name === 'OrderCheck'"
                v-hasPermi="['system:orderCheck:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'OrderCheck' &&
                  [1, 2].includes(row.orderCheckStatus) &&
                  row.auditStatus == 1
                "
                v-hasPermi="['system:orderCheck:check']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="route.name === 'Order' && row.orderCheckStatus == 3"
                v-hasPermi="['system:orderCheck:change']"
                title="变更"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('change', row)"
              >
                <!-- <EditPen /> -->
                <img
                  src="@/assets/icons/images/alter.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
              <!-- -->
              <el-icon
                v-if="
                  route.name === 'Order' &&
                  [0, 5].includes(row.orderCheckStatus)
                "
                v-hasPermi="['system:order:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'OrderCheck' &&
                  [0, 5].includes(row.orderCheckStatus) &&
                  false
                "
                v-hasPermi="['system:orderCheck:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="route.name === 'Order' && row.orderCheckStatus == 1"
                v-hasPermi="['system:order:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <!-- <Refresh /> -->
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Order' &&
                  row.checkMaterialStatus === 0 &&
                  [3].includes(row.orderCheckStatus)
                "
                title="完善物料"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('perfect', row)"
              >
                <!-- <Refresh /> -->
                <img
                  src="@/assets/icons/images/perfect.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="采购编号"
          prop="purchaseOrderCode" v-if="checkList.includes('purchaseOrderCode')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDate" v-if="checkList.includes('applicantDate')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="采购人"
          prop="applicantName" v-if="checkList.includes('applicantName')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="采购部门"
          prop="deptName" v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="采购类型"
          prop="purchaseOrderTypeName" v-if="checkList.includes('purchaseOrderTypeName')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="采购数量"
          prop="purchaseNumSum" v-if="checkList.includes('purchaseNumSum')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.purchaseNumSum ? row.purchaseNumSum : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="采购总金额(元)"
          prop="purchaseAmountSum" v-if="checkList.includes('purchaseAmountSum')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{
              row.purchaseAmountSum ? row.purchaseAmountSum : "--"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          prop="orderCheckStatusName" v-if="checkList.includes('orderCheckStatusName')"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.orderCheckStatusName)">{{
              row.orderCheckStatusName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="下步流程"
          prop="nextNodeName" v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getRequestList"
      />
    </div>
    <RequestAdd
      ref="requestAddRef"
      v-if="requestAddShow"
      v-model:requestAddShow="requestAddShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />
    <RequestDtl
      ref="requestDtlRef"
      v-if="requestDtlShow"
      v-model:requestDtlShow="requestDtlShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import RequestAdd from "./requestAdd.vue";
import RequestDtl from "./dtl.vue";
import { deleteCustomerApi } from "@/api/information/customer";
import { getDictsApi } from "@/api/dict";
import { getRequestListApi, deleteRequestId } from "@/api/purchase/request";
import { getInquiryListApi, deleteInquiryId } from "@/api/purchase/inquiry";
import {
  getOrderListApi,
  deleteOrderId,
  editOrederApi,
  checkErpOrderApi,
  saveCancel,
} from "@/api/purchase/order";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
// 路由
const route = useRoute();
// 搜索参数
const params = reactive({
  applicantName: "", // 申请人名称
  applicantDate: "", // 申请日期
  orderCheckStatus: null, // 审核状态
  purchaseOrderCode: "", //采购订单编号
  purchaseOrderType: null, // 采购类型
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 客户列表
const requestList = ref([]);
// 审核状态列表
const checkOptions = ref([]);
// 采购类型列表
const typeList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const requestAddRef = ref(null);
// 客户新增组件显隐
const requestAddShow = ref(false);

// 客户新增组件引用
const requestDtlRef = ref(null);
// 客户新增组件显隐
const requestDtlShow = ref(false);
// 操作类型
const pageType = ref("");

const checkList = ref([
  "purchaseOrderCode",
  "applicantDate",
  "applicantName",
  "deptName",
  "purchaseOrderTypeName",
  "purchaseNumSum",
  "purchaseAmountSum",
  "orderCheckStatusName",
  "nextNodeName",
]);

/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType:route.name === "Order" ? 17 : 18,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
 const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: route.name === "Order" ? 17 : 18,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    applicantName: "", // 申请人名称
    applicantDate: "", // 申请日期
    orderCheckStatus: null, // 审核状态
    purchaseOrderCode: "", //采购订单编号
    purchaseOrderType: null, // 采购类型
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getRequestList();
};
/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getRequestList();
};
/**
 * @description: 处理导出
 */
const handleExport = async () => {
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
  if (route.name === "Order") {
    /* 导出 */
    proxy.download(
      `/system/orderInfo/selectOrderInfoListExport?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `采购订单管理${fileNmae}.xlsx`,
      null,
      1
    );
  } else {
    /* 导出 */
    proxy.download(
      `/system/orderInfo/selectOrderInfoCheckListExport?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `采购订单审核${fileNmae}.xlsx`,
      null,
      1
    );
  }
};

/**
 * @description: 获取客户列表
 */
const getRequestList = async () => {
  try {
    loading.value = true;
    if (route.name === "Order") {
      params.auditType = 1;
    } else {
      params.auditType = 2;
    }
    let { pageNum, pageSize } = params;
    const res = await getOrderListApi({ pageNum, pageSize }, params);
    requestList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.purchaseOrderId);
      });
      break;
    case "detail":
      pageType.value = type;
      requestDtlShow.value = true;
      nextTick(() => {
        requestDtlRef.value.handleDetailInfo(row.purchaseOrderId);
      });
      break;
    case "change":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.purchaseOrderId);
      });
      break;
    case "check":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.purchaseOrderId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该采购订单，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteOrderId(row.purchaseOrderId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getRequestList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "revoke":
      ElMessageBox.confirm("此操作将撤销该采购订单，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          let param = {
            purchaseOrderId: row.purchaseOrderId,
            orderCheckStatus: 5,
          };
          if (route.name === "Order") {
            param.type = 2;
          }
          const res = await saveCancel(param);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getRequestList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "perfect":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.purchaseOrderId);
      });
      break;
    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 审核状态
  await getDictsApi("erp_inquiry_check_status").then((res) => {
    if (res.code === 200) {
      checkOptions.value = res.data;
    }
  });
  // 类型
  await getDictsApi("purchase_order_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    requestDtlShow.value = true;
    nextTick(() => {
      requestDtlRef.value.handleDetailInfo(Number(applyId));
    });
  }
  getDicts();
  getRequestList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
